package com.hzdp.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.hzdp.crypto.codec.MD5;
import com.hzdp.user.service.UserAccountService;
import com.hzdp.web.ops.remote.RemoteIpGetter;
import com.hzdp.web.util.CookieUtil;

public class ContextFilter implements Filter {

	public static final String name = "UUID";
	public static String Token = "tk";
	public static String ContextUser = "ContextUser";

	private UserAccountService userAccountService;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String beanName = filterConfig.getInitParameter("userAccountServiceBeanName");
		ServletContext servletContext = filterConfig.getServletContext();
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		userAccountService = (UserAccountService) context.getBean(beanName);
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		String cookie = CookieUtil.getCookie(httpRequest, name);
		if (cookie == null || cookie.isEmpty()) {
			String header = httpRequest.getHeader("user-agent");
			String remoteAddr = RemoteIpGetter.getRemoteAddr(httpRequest);
			cookie = MD5.digest(header + remoteAddr + System.currentTimeMillis());
			CookieUtil.setCookie(httpResponse, name, cookie);
		}
		httpRequest.setAttribute(name, cookie);

		String token = CookieUtil.getCookie(httpRequest, Token);
		if (userAccountService != null) {
			int userId = userAccountService.parseToken(token);
			if (userId > 0) {
				request.setAttribute(ContextUser, userId);
			}
		}
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
	}

}
